package com.atguigu.gmall.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * SprintCloud内部拦截器，每次远程发送请求，都会尝试给新的request带上请求头
 * @author dyqstart
 * @create 2021-08-17-20:14
 * @since 1.0.0
 */
@Configuration
public class AppFeignConfig {


//    @Bean
//    RequestInterceptor headerRequestInterceptor(){
//        RequestInterceptor interceptor = new RequestInterceptor() {
//            @Override
//            public void apply(RequestTemplate template) {
//                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//                HttpServletRequest request = requestAttributes.getRequest();
//                String userId = request.getHeader("userId");
//                String userTempId = request.getHeader("userTempId");
//                template.header("userId",userId);
//                template.header("userTempId",userTempId);
//            }
//        };
//        return interceptor;
//    }


    @Bean
    public RequestInterceptor headerRequestInterceptor(){
        return (template)->{
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            //从前面的请求头里获取到核心信息
            String userId = request.getHeader("userId");
            String userTempId = request.getHeader("userTempId");
            template.header("userId", userId);
            template.header("userTempId", userTempId);
        };
    };
}
